package com.jiyun.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.jiyun.entity.*;
import com.jiyun.service.*;
import com.jiyun.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@RequestMapping("login")
public class LoginController {

    @Autowired
    IJiyunUserService jiyunUserService;

    @RequestMapping("weblogin")
    public Map weblogin(@RequestBody JiyunUser jiyunUser,@RequestHeader(value = "token",required = false) String token){

        if(StringUtils.isNotBlank(token)){

            Claims claims = jwtUtil.parseJWT(token);
            Date expiration = claims.getExpiration();

//        JiyunUser userInfo = claims.get("userInfo", JiyunUser.class);
            LinkedHashMap userInfo = (LinkedHashMap)claims.get("userInfo");
            List roleList = claims.get("roleList", List.class);
            List menuList = claims.get("menuList", List.class);


            System.out.println("---------------------------");
            System.out.println(expiration);
            System.out.println(userInfo);
            System.out.println(roleList);
            System.out.println("---------------------------");


            HashMap r = new HashMap();
            r.put("code",0);
            r.put("msg","登录成功");

            HashMap dataMap = new HashMap();
            dataMap.put("roleList",roleList);
            dataMap.put("menuList",menuList);
            dataMap.put("userInfo",userInfo);
            r.put("data",dataMap);


            return r;


        }

        /**
         * code:0成功/1失败
         * data:{
         *      token
         *      roleList
         *      menuList
         * }
         * msg:"状态信息"
         */
        HashMap result = new HashMap();

        /**
         * 1、是否登录
         *  是：
         *      返回登录成功，用时返回用户信息
         *  否：
         *      账号是否存在
         *      密码是否正确
         *      账号状态是否正常
         *      账号所在租户是否正常
         *    所有都校验通过之后，返回token以及用户信息
         */

        LambdaQueryWrapper<JiyunUser> jiyunUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        jiyunUserLambdaQueryWrapper.eq(JiyunUser::getUsername,jiyunUser.getUsername());

        JiyunUser jiyunUserDB = jiyunUserService.getOne(jiyunUserLambdaQueryWrapper);

        //校验账号是否存在
        if (jiyunUserDB==null) {
            result.put("code",1);
            result.put("msg","账号不存在");
            return result;
        }
        //校验密码是否正确
        if (!jiyunUserDB.getPassword().equals(jiyunUser.getPassword())) {
            result.put("code",1);
            result.put("msg","密码不正确");
            return result;
        }
        //校验账号状态
        if (!jiyunUserDB.getStatus().equals("0")) {
            result.put("code",1);
            result.put("msg","账号状态异常，不能登录");
            return result;
        }

        //校验租户状态
        Tenant tenant = tenantService.getById(jiyunUserDB.getTenantId());
        if (!tenant.getEnable().equals("1")) {
            result.put("code",1);
            result.put("msg","租户禁用，不能登录");
            return result;
        }

        //到此校验成功
        //查询角色和权限信息
        /**
         * 已知条件：用户id
         * 1、查询 用户角色中间表--查询出角色id信息
         * 2、根据角色id信息，查询角色list
         * 3、查询 角色菜单中间表 --查询出菜单id信息
         * 4、根据菜单id信息，查询出菜单list
         */
        //1、查询 用户角色中间表--查询出角色id信息
        LambdaQueryWrapper<UserRole> userRoleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userRoleLambdaQueryWrapper.eq(UserRole::getUid,jiyunUserDB.getId());
        List<UserRole> userRoleList = userRoleService.list(userRoleLambdaQueryWrapper);

        //得到所有的角色id
        ArrayList<Integer> roleIds = new ArrayList<>();
        for (UserRole userRole : userRoleList) {
            roleIds.add(userRole.getRid());
        }
        //2、根据角色id信息，查询角色list
        LambdaQueryWrapper<Role> roleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        roleLambdaQueryWrapper.in(Role::getId,roleIds);
        List<Role> roleList = roleService.list(roleLambdaQueryWrapper);

        //3、查询 角色菜单中间表 --查询出菜单id信息
        LambdaQueryWrapper<RoleMenu> roleMenuLambdaQueryWrapper = new LambdaQueryWrapper<>();
        roleMenuLambdaQueryWrapper.in(RoleMenu::getRid,roleIds);
        List<RoleMenu> roleMenuList = roleMenuService.list(roleMenuLambdaQueryWrapper);
        //得到所有的角色id
        ArrayList<Integer> menuIds = new ArrayList<>();
        for (RoleMenu roleMenu : roleMenuList) {
            menuIds.add(roleMenu.getMid());
        }


        //4、根据菜单id信息，查询出菜单list
        LambdaQueryWrapper<Menu> menuLambdaQueryWrapper = new LambdaQueryWrapper<>();
        menuLambdaQueryWrapper.in(Menu::getId,menuIds);
        List<Menu> menuList = menuService.list(menuLambdaQueryWrapper);


        //存放登录成功之后的角色、权限以及token信息
        HashMap dataMap = new HashMap();
        dataMap.put("roleList",roleList);
        dataMap.put("menuList",menuList);
        dataMap.put("userInfo",jiyunUserDB);

        //使用jwt生成token
        Date date = new Date();//当前时间
        Date expDate = new Date(date.getTime() + 1000 * 60 * 60 * 24 * 3);
        token = jwtUtil.createJWT(expDate,dataMap);

        dataMap.put("token",token);

        result.put("data",dataMap);






        return result;
    }

    @Autowired
    JwtUtil jwtUtil;

    @Autowired
    ITenantService tenantService;

    @Autowired
    IUserRoleService userRoleService;

    @Autowired
    IRoleService roleService;

    @Autowired
    IRoleMenuService roleMenuService;

    @Autowired
    IMenuService menuService;



    @RequestMapping("yanzheng")
    public void yanzheng(@RequestHeader("token") String token){
        System.out.println(token);
        Claims claims = jwtUtil.parseJWT(token);
        Date expiration = claims.getExpiration();

//        JiyunUser userInfo = claims.get("userInfo", JiyunUser.class);
        LinkedHashMap userInfo = (LinkedHashMap)claims.get("userInfo");
        List roleList = claims.get("roleList", List.class);


        System.out.println("---------------------------");
        System.out.println(expiration);
        System.out.println(userInfo);
        System.out.println(roleList);
        System.out.println("---------------------------");

    }






}
